package chapter23;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/27 14:40
 */
public class SimpleJDKDynamicProxyDemo {
    public static void main(String[] args) {
        Iservice realServie = new RealService();
        Iservice porxy = (Iservice) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class<?>[]{Iservice.class}, new SimpleInvocationHandler(realServie));
        porxy.sayHello();
    }

    static interface Iservice {
        public void sayHello();
    }

    static class RealService implements Iservice {
        @Override
        public void sayHello() {
            System.out.println("hello");
        }
    }

    static class SimpleInvocationHandler implements InvocationHandler {
        private Object realObj;

        public SimpleInvocationHandler(Object realObj) {
            this.realObj = realObj;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("entering " + method.getName());
            Object result = method.invoke(realObj, args);
            System.out.println("leaving " + method.getName());
            return result;
        }
    }

}
